package com.codyy.mobile.support.chart;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.RectF;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * 双柱状图+单折线图
 * created by lijian on 2019/12/17
 */
public class BarChartView extends ViewGroup {
    private int paddingStart;
    private int paddingEnd;
    private int paddingBottom;
    private int coordinateSpaceY;
    private Chart chart;
    private CoordinateView bg;
    private Paint topPaint;
    private final String seriesFirstName;
    private final String seriesSecondName;
    private final String seriesThirdName;
    private final String defaultTip;
    private final String yAxisLabel;
    private final String yyAxisLabel;

    public BarChartView(Context context) {
        this(context, null);
    }

    public BarChartView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BarChartView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setWillNotDraw(false);
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.BarChartView, defStyleAttr, 0);
        try {
            seriesFirstName = a.getString(R.styleable.BarChartView_seriesFirstName);
            seriesSecondName = a.getString(R.styleable.BarChartView_seriesSecondName);
            seriesThirdName = a.getString(R.styleable.BarChartView_seriesThirdName);
            defaultTip = a.getString(R.styleable.BarChartView_defaultTip);
            yAxisLabel = a.getString(R.styleable.BarChartView_yAxisLabel);
            yyAxisLabel = a.getString(R.styleable.BarChartView_yyAxisLabel);
        } finally {
            a.recycle();
        }
        initAttrs();
        initView(context);
    }

    private void initAttrs() {
        paddingStart = dip2px(43f);
        paddingEnd = dip2px(43f);
        paddingBottom = dip2px(15f);
        coordinateSpaceY = dip2px(30f);
    }

    private void initView(Context context) {
        topPaint = new Paint();
        topPaint.setStyle(Paint.Style.FILL);
        topPaint.setTextSize(dip2px(12f));
        topPaint.setAntiAlias(true);
        topPaint.setDither(true);
        bg = new CoordinateView(context);
        bg.setSeriesFirstName(seriesFirstName);
        bg.setSeriesSecondName(seriesSecondName);
        bg.setSeriesThirdName(seriesThirdName);
        bg.setDefaultTip(defaultTip);
        bg.setyAxisLabel(yAxisLabel);
        bg.setYyAxisLabel(yyAxisLabel);
        addView(bg);
        HorizontalScrollView scrollView = new HorizontalScrollView(context);
        scrollView.setOverScrollMode(OVER_SCROLL_NEVER);
        scrollView.setHorizontalScrollBarEnabled(false);
        chart = new Chart(context);
        scrollView.addView(chart, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
        addView(scrollView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
    }

    private final RectF sign = new RectF();

    @Override
    public void onDrawForeground(Canvas canvas) {
        super.onDrawForeground(canvas);
        if (TextUtils.isEmpty(seriesFirstName) || TextUtils.isEmpty(seriesSecondName) || TextUtils.isEmpty(seriesThirdName)) {
            return;
        }
        int startX = (getMeasuredWidth() - dip2px(259)) / 2;
        float stopY = getTextHeight(topPaint) + dip2px(8f);
        topPaint.setColor(Color.parseColor("#666666"));
        canvas.drawText(seriesFirstName, startX, stopY, topPaint);
        sign.right = startX - dip2px(4f);
        sign.left = sign.right - dip2px(8f);
        sign.top = (stopY - getTextHeight(topPaint) / 2) - dip2px(1f);
        sign.bottom = sign.top + dip2px(8f);
        topPaint.setColor(Color.parseColor("#3ddf9c"));
        canvas.drawRoundRect(sign, dip2px(2f), dip2px(2f), topPaint);
        startX += (dip2px(32f) + topPaint.measureText(seriesFirstName));
        topPaint.setColor(Color.parseColor("#666666"));
        canvas.drawText(seriesSecondName, startX, stopY, topPaint);
        sign.right = startX - dip2px(4f);
        sign.left = sign.right - dip2px(8f);
        topPaint.setColor(Color.parseColor("#347eff"));
        canvas.drawRoundRect(sign, dip2px(2f), dip2px(2f), topPaint);
        startX += (dip2px(32f) + topPaint.measureText(seriesSecondName));
        topPaint.setColor(Color.parseColor("#666666"));
        canvas.drawText(seriesThirdName, startX, stopY, topPaint);
        sign.right = startX - dip2px(4f);
        sign.left = sign.right - dip2px(8f);
        topPaint.setColor(Color.parseColor("#fe9727"));
        canvas.drawRoundRect(sign, dip2px(2f), dip2px(2f), topPaint);

    }

    /**
     * 计算绘制文字时的基线到中轴线的距离
     *
     * @return 基线和centerY的距离
     */
    private float getBaseline(Paint p) {
        Paint.FontMetrics fontMetrics = p.getFontMetrics();
        return (fontMetrics.descent - fontMetrics.ascent) / 2 - fontMetrics.descent;
    }

    private float getTextHeight(Paint p) {
        Paint.FontMetrics fontMetrics = p.getFontMetrics();
        return Math.abs(fontMetrics.ascent) + Math.abs(fontMetrics.descent);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        getChildAt(0).layout(0, dip2px(20f), getMeasuredWidth(), getMeasuredHeight());
        getChildAt(1).layout(paddingStart, getMeasuredHeight() - coordinateSpaceY * 5 - dip2px(43f), getMeasuredWidth() - paddingEnd, getMeasuredHeight() - paddingBottom);
    }

    public void setData(@NonNull int[] bar1, @NonNull int[] bar2, @NonNull int[] line, @NonNull String[] xLabels) {
        if (!(bar1.length == bar2.length && bar1.length == line.length && bar1.length == xLabels.length && bar1.length > 0)) {
            throw new IllegalArgumentException("参数长度必须相等");
        }
        int maxY = 0;
        for (int b : bar1) {
            if (maxY < b) {
                maxY = b;
            }
        }
        for (int b : bar2) {
            if (maxY < b) {
                maxY = b;
            }
        }
        int maxYY = 0;
        for (int l : line) {
            if (maxYY < l) {
                maxYY = l;
            }
        }
        //纵坐标-开课量：坐标参数最大值，取“计划课时数和实开课时数”中的最大值，然后进百。举例：232进百，为300
        int realMaxY = maxY % 100 == 0 ? maxY : (maxY - maxY % 100 + 100);
        //纵坐标-比例：坐标参数最大值，取“实开课时占比”中的最大值，然后进十。举例：102%进十，为110%
        int realMaxYY = maxYY % 10 == 0 ? maxYY : (maxYY - maxYY % 10 + 10);
        bg.setMax(realMaxY, realMaxYY);
        chart.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(int y, int yy, String percent) {
                bg.setTip(y, yy, percent);
            }

            @Override
            public void onCancel() {
                bg.cancelTip();
            }
        });
        chart.setData(bar1, bar2, line, xLabels, realMaxY, realMaxYY);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int count = getChildCount();
        for (int i = 0; i < count; ++i) {
            View childView = getChildAt(i);
            measureChild(childView,
                    widthMeasureSpec, heightMeasureSpec);
        }
        setMeasuredDimension(getSize(widthMeasureSpec), dip2px(245f));
    }

    private int getSize(int widthMeasureSpec) {
        int result;
        int specMode = MeasureSpec.getMode(widthMeasureSpec);
        int specSize = MeasureSpec.getSize(widthMeasureSpec);
        switch (specMode) {
            case MeasureSpec.EXACTLY://match_parent or 确切大小40dp
                result = specSize;//确切大小,所以将得到的尺寸给view
                break;
            case MeasureSpec.AT_MOST://wrap_content
                //默认值为450px,此处要结合父控件给子控件的最多大小(要不然会填充父控件),所以采用最小值
                result = Math.min(450, specSize);
                break;
            case MeasureSpec.UNSPECIFIED://未指定
            default:
                result = 450;
                break;
        }
        return result;
    }

    private int dip2px(float dip) {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (dip * scale + 0.5f);
    }

    private class Chart extends View {
        //折线图路径
        private final Path path = new Path();
        private final Paint paint;
        private final RectF mRectF;
        private int count = 0;
        private final int dp8;
        private final int dp150;
        private final int dp20;
        private final int dp40;
        private final int dp4;
        private final int dp10;
        private final int xSpaceDp50;
        private final float barRadius;
        private final float divider;
        private final float barWidth;
        private final int circleRadius;
        //用于判断手指是否滑动
        private final float mTouchSlop;
        private int[] bar1 = new int[]{};
        private int[] bar2 = new int[]{};
        private int[] line = new int[]{};
        private String[] xLabels = new String[]{};
        //y1轴最大值
        private int maxY = 300;
        //y2轴最大值
        private int maxYY = 100;
        private BarChartView.OnClickListener onClickListener;

        public void setOnClickListener(BarChartView.OnClickListener onClickListener) {
            this.onClickListener = onClickListener;
        }

        /**
         * 设置图表数据
         *
         * @param bar1    柱状图1
         * @param bar2    柱状图2
         * @param line    折线图
         * @param xLabels x轴坐标文字
         * @param maxY    y轴1最大值
         * @param maxYY   y轴2最大值
         */
        public void setData(@NonNull int[] bar1, @NonNull int[] bar2, @NonNull int[] line, @NonNull String[] xLabels, int maxY, int maxYY) {
            this.maxY = maxY;
            this.maxYY = maxYY;
            this.bar1 = bar1;
            this.bar2 = bar2;
            this.line = line;
            this.xLabels = xLabels;
            this.count = bar1.length;
            requestLayout();
        }

        public Chart(Context context) {
            this(context, null);
        }

        public Chart(Context context, @Nullable AttributeSet attrs) {
            this(context, attrs, 0);
        }

        public Chart(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
            dp8 = dip2px(8f);
            dp150 = dip2px(150f);
            dp20 = dip2px(20f);
            dp40 = dip2px(40f);
            dp4 = dip2px(4f);
            barRadius = dp4;
            dp10 = dip2px(10f);
            xSpaceDp50 = dip2px(50f);
            divider = dip2px(2f);//柱状图间距
            circleRadius = dip2px(3f);//柱状图间距
            barWidth = dp8;
            paint = new Paint();
            paint.setStrokeWidth(dip2px(1f));
            paint.setTextSize(dp10);
            paint.setDither(true);
            paint.setAntiAlias(true);
            mRectF = new RectF();
        }

        private float getBarTop(int bar) {
            return -bar * 1f / maxY * dp150;
        }

        private float getLineY(int line) {
            return -line * 1f / maxYY * dp150;
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            canvas.translate(0, dp150 + dp10);
            path.reset();
            for (int i = 0; i < count; i++) {
                int centerX = i * xSpaceDp50 + dp20;//X轴没分隔中心点x坐标
                //绘制按压效果
                paint.setStyle(Paint.Style.FILL);
                if (isPressDown && lastPoint.x >= centerX - dp10 && lastPoint.x <= centerX + dp10) {
                    paint.setColor(Color.parseColor("#eeeeee"));
                    canvas.drawRect(i * xSpaceDp50, -dp150, i * xSpaceDp50 + dp20 * 2, 0, paint);
                    if (onClickListener != null) {
                        onClickListener.onClick(bar1[i], bar2[i], line[i] + "%");
                    }
                }

                //绘制柱状图1
                paint.setColor(Color.parseColor("#3ddf9c"));

                //RectF.left=centerX-divider/2-barWidth;RectF.right=centerX-divider/2
                mRectF.set(centerX - divider / 2 - barWidth, getBarTop(bar1[i]), centerX - divider / 2, 0);
                canvas.drawRoundRect(mRectF, barRadius, barRadius, paint);
                //绘制柱状图2,RectF.left=centerX+divider/2;RectF.right=centerX+divider/2+barWidth
                paint.setColor(Color.parseColor("#347eff"));
                mRectF.set(centerX + divider / 2, getBarTop(bar2[i]), centerX + divider / 2 + barWidth, 0);
                canvas.drawRoundRect(mRectF, barRadius, barRadius, paint);
                //设置折线图path，准备绘制
                if (i == 0) {
                    path.moveTo(centerX, getLineY(line[i]));
                } else {
                    path.lineTo(centerX, getLineY(line[i]));
                }
                //绘制x轴Label
                paint.setColor(Color.parseColor("#666666"));
                canvas.drawText(xLabels[i], getTextStartX(xLabels[i], i * xSpaceDp50), dp10 + getBaseline(paint), paint);
            }
            //绘制折线图
            paint.setStyle(Paint.Style.STROKE);
            paint.setColor(Color.parseColor("#fe9727"));
            canvas.drawPath(path, paint);
            //绘制折线图上的圆点
            for (int i = 0; i < count; i++) {
                int centerX = i * xSpaceDp50 + dp20;//X轴没分隔中心点x坐标
                paint.setStyle(Paint.Style.FILL);
                paint.setColor(Color.parseColor("#FFFFFF"));
                //绘制白色实心圆
                canvas.drawCircle(centerX, getLineY(line[i]), circleRadius, paint);
                paint.setStyle(Paint.Style.STROKE);
                //绘制黄色空心圆
                paint.setColor(Color.parseColor("#fe9727"));
                canvas.drawCircle(centerX, getLineY(line[i]), circleRadius, paint);
            }
        }

        private int getTextStartX(String text, int position) {
            float textWidth = paint.measureText(text);
            return (int) (position + (dp40 - textWidth) / 2);
        }

        private final PointF lastPoint = new PointF(0, 0);
        private boolean isPressDown;

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            //禁止多指触摸
            if (event.getPointerCount() > 1) {
                return super.onTouchEvent(event);
            }
            //拦截Down事件
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                lastPoint.x = event.getX();
                lastPoint.y = event.getY();
                isPressDown = true;
                postInvalidate();
                return true;
            } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                return Math.abs(event.getX() - lastPoint.x) <= mTouchSlop;//大于滑动距离，判断为滑动

            } else if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
                if (onClickListener != null) {
                    onClickListener.onCancel();
                }
                //取消按压状态
                isPressDown = false;
                postInvalidate();
            }

            return super.onTouchEvent(event);
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            setMeasuredDimension(getSize(widthMeasureSpec), dip2px(174f));
        }

        private int getSize(int widthMeasureSpec) {
            int result;
            int specMode = MeasureSpec.getMode(widthMeasureSpec);
            int specSize = MeasureSpec.getSize(widthMeasureSpec);
            switch (specMode) {
                case MeasureSpec.EXACTLY://match_parent or 确切大小40dp
                    result = specSize;//确切大小,所以将得到的尺寸给view
                    break;
                case MeasureSpec.AT_MOST://wrap_content
                    //默认值为450px,此处要结合父控件给子控件的最多大小(要不然会填充父控件),所以采用最小值
                    result = Math.min(count * dip2px(50f), specSize);
                    break;
                case MeasureSpec.UNSPECIFIED://未指定
                default:
                    result = count * dip2px(50f);
                    break;
            }
            return result;
        }

        /**
         * 计算绘制文字时的基线到中轴线的距离
         *
         * @return 基线和centerY的距离
         */
        private float getBaseline(Paint p) {
            Paint.FontMetrics fontMetrics = p.getFontMetrics();
            return (fontMetrics.descent - fontMetrics.ascent) / 2 - fontMetrics.descent;
        }

        private float getTextHeight(Paint p) {
            Paint.FontMetrics fontMetrics = p.getFontMetrics();
            return Math.abs(fontMetrics.ascent) + Math.abs(fontMetrics.descent);
        }
    }

    /**
     * 坐标系,背景图
     */
    private static class CoordinateView extends View {
        private Paint mPaint;
        private int colorDivider;
        private int colorXYCoordinateText;
        private int colorTipText;
        private TextPaint mTextPaintCoordinate;
        private int paddingStart;
        private int paddingEnd;
        private int paddingBottom;
        private int width;
        private int height;
        private int lineLength;
        private int lineWidth;
        //分割高度,默认30dp
        private int coordinateSpaceY;
        //y1轴最大值
        private final int maxY = 300;
        //y1轴平均间隔值
        private int ySpace = 60;
        //y2轴最大值
        private final int maxYY = 100;
        //y2轴平均间隔值
        private int yYSpace = 20;
        //坐标轴文本字体大小 10sp
        private int coordinateTextSize;
        //坐标轴文本与坐标系间距 6dp
        private int coordinateTextMargin;
        private String defaultTip = "";
        private String tip = "";
        private String seriesFirstName;
        private String seriesSecondName;
        private String seriesThirdName;
        private String yAxisLabel;
        private String yyAxisLabel;

        public CoordinateView(Context context) {
            this(context, null);
        }

        public CoordinateView(Context context, AttributeSet attrs) {
            this(context, attrs, 0);
        }

        public CoordinateView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            initAttrs();
            initPaint();
        }

        private void initPaint() {
            colorDivider = Color.parseColor("#f6f6f6");
            colorXYCoordinateText = Color.parseColor("#939fbe");
            colorTipText = Color.parseColor("#999999");
            mPaint = new Paint();
            mPaint.setAntiAlias(true);
            mPaint.setStyle(Paint.Style.FILL);
            mPaint.setStrokeWidth(lineWidth);
            mTextPaintCoordinate = new TextPaint();
            mTextPaintCoordinate.setAntiAlias(true);
            mTextPaintCoordinate.setColor(colorXYCoordinateText);
            mTextPaintCoordinate.setTextSize(coordinateTextSize);
        }

        public void setDefaultTip(String defaultTip) {
            this.defaultTip = defaultTip;
            this.tip=defaultTip;
        }

        public void setyAxisLabel(String yAxisLabel) {
            this.yAxisLabel = yAxisLabel;
        }

        public void setYyAxisLabel(String yyAxisLabel) {
            this.yyAxisLabel = yyAxisLabel;
        }

        public void setSeriesFirstName(String seriesFirstName) {
            this.seriesFirstName = seriesFirstName;
        }

        public void setSeriesSecondName(String seriesSecondName) {
            this.seriesSecondName = seriesSecondName;
        }

        public void setSeriesThirdName(String seriesThirdName) {
            this.seriesThirdName = seriesThirdName;
        }

        @Override
        protected void onSizeChanged(int w, int h, int oldw, int oldh) {
            super.onSizeChanged(w, h, oldw, oldh);
            width = w;
            height = h;
            lineLength = width - paddingStart - paddingEnd;
        }

        private void initAttrs() {
            paddingStart = dip2px(43f);
            paddingEnd = dip2px(43f);
            paddingBottom = dip2px(33f);
            coordinateSpaceY = dip2px(30f);
            lineWidth = dip2px(1f);
            coordinateTextMargin = dip2px(6f);
            coordinateTextSize = sp2px(10f);
        }

        /**
         * 坐标系
         * canvas.translate(paddingStart, height - paddingBottom);
         * |-----------*
         * -  |-----------*
         * |-----------*
         * **********************
         * *
         * *  +
         * *
         */
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            //设置分割线画笔颜色及粗细
            mPaint.setColor(colorDivider);
            //移动坐标系
            canvas.translate(paddingStart, height - paddingBottom);
            mTextPaintCoordinate.setColor(colorXYCoordinateText);
            //绘制6条分割线
            for (int i = 0; i < 6; i++) {
                canvas.drawLine(0, -i * coordinateSpaceY, lineLength, -i * coordinateSpaceY, mPaint);
                canvas.drawText(ySpace * i + "", -coordinateTextMargin - mTextPaintCoordinate.measureText(ySpace * i + ""), -coordinateSpaceY * i + getBaseline(mTextPaintCoordinate), mTextPaintCoordinate);
                canvas.drawText(yYSpace * i + "%", lineLength + coordinateTextMargin, -coordinateSpaceY * i + getBaseline(mTextPaintCoordinate), mTextPaintCoordinate);
            }
            //绘制Y轴描述文字
            int i = 5;
            if (!TextUtils.isEmpty(yAxisLabel)) {
                canvas.drawText(yAxisLabel, -coordinateTextMargin - mTextPaintCoordinate.measureText(yAxisLabel), getYTipMarginBottom(i), mTextPaintCoordinate);
            }
            if (!TextUtils.isEmpty(yyAxisLabel)) {
                canvas.drawText(yyAxisLabel, lineLength + coordinateTextMargin, getYTipMarginBottom(i), mTextPaintCoordinate);
            }
            //绘制顶部中间文本
            if (defaultTip.equals(tip) || TextUtils.isEmpty(tip)) {
                mTextPaintCoordinate.setColor(colorTipText);
                canvas.drawText(tip, (lineLength - mTextPaintCoordinate.measureText(tip)) / 2, getYTipMarginBottom(i), mTextPaintCoordinate);
            } else {
                float startX = (lineLength - mTextPaintCoordinate.measureText(tip)) / 2;
                String[] tips = tip.split("，");
                for (int pos = 0; pos < tips.length; pos++) {
                    String prefix = tips[pos].substring(0, tips[pos].lastIndexOf("：") + 1);
                    String value = tips[pos].substring(tips[pos].lastIndexOf("：") + 1);
                    prefix = (pos == 0 ? prefix : ("，" + prefix));
                    //绘制前缀文本
                    mTextPaintCoordinate.setColor(Color.BLACK);
                    canvas.drawText(prefix, startX, getYTipMarginBottom(i), mTextPaintCoordinate);
                    //绘制彩色文字
                    startX += mTextPaintCoordinate.measureText(prefix);
                    if (pos == 0) {
                        mTextPaintCoordinate.setColor(Color.parseColor("#3ddf9c"));//绿
                    } else if (pos == 1) {
                        mTextPaintCoordinate.setColor(Color.parseColor("#347eff"));//蓝
                    } else {
                        mTextPaintCoordinate.setColor(Color.parseColor("#fe9727"));//黄
                    }
                    canvas.drawText(value, startX, getYTipMarginBottom(i), mTextPaintCoordinate);
                    startX += mTextPaintCoordinate.measureText(value);

                }
            }
        }

        private float getYTipMarginBottom(int i) {
            return -coordinateSpaceY * i - lineWidth * 4 - getTextHeight(mTextPaintCoordinate) + getBaseline(mTextPaintCoordinate);
        }

        /**
         * 计算绘制文字时的基线到中轴线的距离
         *
         * @return 基线和centerY的距离
         */
        private float getBaseline(Paint p) {
            Paint.FontMetrics fontMetrics = p.getFontMetrics();
            return (fontMetrics.descent - fontMetrics.ascent) / 2 - fontMetrics.descent;
        }

        private float getTextHeight(Paint p) {
            Paint.FontMetrics fontMetrics = p.getFontMetrics();
            return Math.abs(fontMetrics.ascent) + Math.abs(fontMetrics.descent);
        }

        /**
         * Y轴1
         *
         * @param max 最大值
         */
        public void setYMax(int max) {
            this.ySpace = max / 5;
            invalidate();
        }

        public void setMax(int yMax, int yyMax) {
            this.ySpace = yMax / 5;
            this.yYSpace = yyMax / 5;
            invalidate();
        }

        public void setTip(int y, int yy, String percent) {
            this.tip = seriesFirstName + "：" + y + "，" + seriesSecondName + "：" + yy + " ，" + seriesThirdName + "：" + percent;
            postInvalidate();
        }

        public void cancelTip() {
            if (!defaultTip.equals(this.tip)) {
                this.tip = defaultTip;
                postInvalidate();
            }
        }

        /**
         * Y轴2
         *
         * @param max 最大值
         */
        public void setYYMax(int max) {
            this.yYSpace = max / 5;
            invalidate();
        }

        private int dip2px(float dip) {
            final float scale = getResources().getDisplayMetrics().density;
            return (int) (dip * scale + 0.5f);
        }

        private int sp2px(float sp) {
            final float scale = getResources().getDisplayMetrics().scaledDensity;
            return (int) (sp * scale + 0.5f);
        }

    }


    public interface OnClickListener {
        /**
         * 点击事件
         *
         * @param y       柱状图1 y轴坐标值
         * @param yy      柱状图2 y轴坐标值
         * @param percent 折线图 y轴坐标值:80%
         */
        void onClick(int y, int yy, String percent);

        /**
         * 点击失效
         */
        void onCancel();
    }

}
